package com.miandian.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Component
public class JwtUtil {
    private String secret = "caiyuanqing";
    public String createToken(Long id,String username,Integer isManager){
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",id);
        claims.put("name",username);
        claims.put("isManager",isManager);

        //构建JWT令牌
        String jwt = Jwts.builder().signWith(SignatureAlgorithm.HS256,secret)//算法 秘钥 = 签名算法
                .setClaims(claims)//自定义内容=载荷
                .setExpiration(new Date(System.currentTimeMillis()+3600*10000)) //设置有效期
                .compact();//至此生成
        return jwt;
    }
    //解析JWT
    public Map parseJwt(String token){
        Claims cla = Jwts.parser()
                .setSigningKey("caiyuanqing")
                .parseClaimsJws(token)
                // 拿到自定义部分
                .getBody();
        return cla;
    }
}
